import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';


import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/StringEncapsulation.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'SetPaymentPassword.dart';
import 'VerifyCardMobile.dart';
import 'package:image/image.dart' as img;
class AddBankCard extends StatefulWidget {
  const AddBankCard({super.key});

  @override
  State<AddBankCard> createState() => _AddBankCardState();
}

class _AddBankCardState extends State<AddBankCard> {
  TextEditingController _nametextEditingController = TextEditingController();
  TextEditingController _numbertextEditingController = TextEditingController();
  final ImagePicker picker = new ImagePicker();
  Map userMap={};
  String bankName="";
  String smsCode="";
  String bankNum="";
  File? _bankImage;
  String imagePath="";
  String type="";
  late Timer _timer;
  int curentTimer=0;
  String validCodeReqNo="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo();

  }
  void getUserInfo(){
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/shipper/user/getLoginUser', // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          userMap=responseData['data'];
        });
      },
    );
  }
  //获取银行卡信息
 void uploadSingleFile(String fileData)  {
    ApiManager.postData(
      context,
      'api/system/dev/ocr/doOcr',
      {
        "type":"BC",
        "frontData":fileData,
        "frontFileFormat":"jpg"
      },
          (responseData) {
        setState(() {
          bankNum=responseData['data']['result']['result']['card_number'];
          bankName=responseData['data']['result']['result']['bank_name'];
          type=responseData['data']['result']['result']['type'];
          _nametextEditingController.text=bankName;
          _numbertextEditingController.text=bankNum;
        });
      },
    );

  }

  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    uploadSingleFile(base64String);

  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text('添加银行卡',style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body:userMap.isEmpty?Container(): Column(
          children: [
      Expanded(child:

      ListView(
        children: [
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(top: 14.h,left: 10.w,right: 10.w,bottom: 14.h),
            decoration: BoxDecoration(
              color:Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("用户认证信息",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                SizedBox(height: 15.h,),
                Row(
                  children: [
                    Text("姓名",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    SizedBox(width: 45.w,),
                    Text(userMap['realName'],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                SizedBox(height: 8.h,),
                Row(
                  children: [
                    Text("身份证号",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    SizedBox(width: 20.w,),
                    Text(maskIdNumber(userMap['idNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(top: 14.h,left: 10.w,right: 10.w,bottom: 14.h),
            decoration: BoxDecoration(
              color:Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("输入卡号和发卡行",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                SizedBox(height: 15.h,),
                Row(
                  children: [
                    Text("卡号",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    SizedBox(width: 40.w,),
                    Container(
                      width: screenSize.width-130.w,
                      padding: EdgeInsets.only(left: 8.w,right: 8.w),
                      decoration: BoxDecoration(
                        color:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [

                          Container(
                            width:180.w,
                            child:TextField(
                              controller: _numbertextEditingController,
                              decoration: InputDecoration(
                                hintText: '点击输入本人银行卡号',
                                hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                filled: true,
                                fillColor:Colors.white,
                                border: InputBorder.none,
                                alignLabelWithHint: true,
                                contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                              ),
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.left,
                              style: TextStyle(color: Colors.black),
                              onChanged: (value) {
                                setState(() {
                                  bankNum=value;
                                });
                              },
                            ),
                          ),
                          GestureDetector(
                            child: Icon(Icons.photo_camera,color: MyColors.authTipColor,),
                            onTap: (){
                              showModalBottomSheet(context: context, builder: (BuildContext context)
                              {
                                return Container(
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(Radius.circular(10)),
                                  ),
                                  child:
                                  Stack(

                                    children: [

                                      Column(
                                        mainAxisSize: MainAxisSize.min,
                                        mainAxisAlignment:MainAxisAlignment.center,

                                        children:[
                                          SizedBox(height: 8.h,),
                                          Row(
                                            mainAxisAlignment:MainAxisAlignment.spaceBetween,
                                            children: [
                                              SizedBox(width: 20.w,),
                                              Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                              IconButton(onPressed: (){
                                                Navigator.of(context).pop();
                                              }, icon:Icon(Icons.close,color: MyColors.textColor,size: 30,)),
                                            ],
                                          ),
                                          SizedBox(height: 18.h,),
                                          Row(
                                            children: [
                                              SizedBox(width: 38.w,),
                                              GestureDetector(
                                                child:   Column(
                                                  children: [
                                                    Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                                    Text(messages["相册"],style: TextStyle(color: Colors.black),),
                                                  ],
                                                ),
                                                onTap: ()async{
                                                  Navigator.of(context).pop();
                                                  final pickedFile = await picker.pickImage(source: ImageSource.gallery);
                                                  if (pickedFile != null) {
                                                    setState(() {
                                                      _bankImage = File(pickedFile.path);
                                                      printImageMemorySize(_bankImage!);
                                                      compressImage(_bankImage!);
                                                    });
                                                  }
                                                  // }
                                                },
                                              ),
                                              SizedBox(width: 38.w,),
                                              GestureDetector(
                                                child: Column(
                                                  children: [
                                                    Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                                    Text(messages["拍照"],style: TextStyle(color: Colors.black),),
                                                  ],
                                                ),
                                                onTap: ()async{
                                                  Navigator.of(context).pop();
                                                  final pickedFile = await picker.pickImage(source: ImageSource.camera);
                                                  if (pickedFile != null) {
                                                    setState(() {
                                                      _bankImage = File(pickedFile.path);
                                                      printImageMemorySize(_bankImage!);
                                                      print(_bankImage);
                                                      compressImage(_bankImage!);
                                                    });
                                                  }
                                                  // }
                                                },
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 40.h,),
                                        ],

                                      ),

                                    ],

                                  ),
                                );
                              }
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8.h,),
                Row(
                  children: [
                    Text("发卡行",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    SizedBox(width: 35.w,),
                    Container(
                      width:180.w,
                      child:TextField(
                        controller: _nametextEditingController,
                        decoration: InputDecoration(
                          hintText: '请输入发卡行',
                          hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                          filled: true,
                          fillColor:Colors.white,
                          border: InputBorder.none,
                          alignLabelWithHint: true,
                          contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                        ),
                        // keyboardType: TextInputType.number,
                        textAlign: TextAlign.left,
                        style: TextStyle(color: Colors.black),
                        onChanged: (value) {
                          setState(() {
                            bankName=value;
                          });
                        },
                      ),
                    ),
                    // Text(bankName,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(top: 14.h,left: 10.w,right: 10.w,bottom: 14.h),
            decoration: BoxDecoration(
              color:Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("验证码验证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                SizedBox(height: 15.h,),
                Row(
                  children: [
                    Text("手机号码",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    SizedBox(width: 20.w,),
                    Text(maskPhoneNumber(userMap['phoneNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                  ],
                ),
                SizedBox(height: 8.h,),
                Row(
                  children: [
                    Text("验证码",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                    Row(
                      children: [
                        SizedBox(width: 20.w,),
                        Container(
                          width: screenSize.width-210.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width:100.w,
                                child:TextField(
                                  decoration: InputDecoration(
                                    hintText: '填写验证码',
                                    hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                                    filled: true,
                                    fillColor:Colors.white,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(color: Colors.black),
                                  onChanged: (value) {
                                    setState(() {
                                      smsCode=value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          height: 25.h ,
                          width:100.w,
                          // margin: EdgeInsets.only(left: 30.w,right: 30.w),
                          decoration: BoxDecoration(
                              color: curentTimer > 0?Color.fromRGBO(223, 223, 223, 1):Color.fromRGBO(231, 112, 27, 0.85),
                              borderRadius: BorderRadius.all(Radius.circular(30))),
                          child: Center(
                            child: GestureDetector(
                              child: curentTimer != 0?Text(curentTimer.toString() +"s",style: TextStyle(color: Colors.white,fontSize: 13.sp,fontWeight: FontWeight.w600),)
                                  :Text("获取验证码",style: TextStyle(color: Colors.white,fontSize: 13.sp,fontWeight: FontWeight.w600),),
                              onTap: (){

                                NoLoadingApiManager.postData(
                                  context,
                                  'api/auth/sms/sendPhoneValidCode',
                                  {
                                    "phone": userMap['phoneNum'],
                                    "clientType": "SHIPPER",
                                    "codeType": "BIND_BANK"
                                  },
                                      (responseData)  {
                                        setState(() {
                                          curentTimer = 60;
                                          _timer = Timer.periodic(Duration(seconds: 1), (timer) {
                                            curentTimer--;
                                            if (curentTimer == 0) {
                                              _timer.cancel();
                                              if (mounted) {
                                                setState(() {}); // 刷新状态以使按钮可点击
                                              }
                                            }
                                            if (!mounted) {
                                              _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
                                            }
                                            setState(() {});
                                          });
                                        });
                                      validCodeReqNo=responseData['data']['validCodeReqNo'];

                                  },
                                );
                              },
                            ),
                          ),


                        ),
                        // TimerCode(phoneNumber: userMap['phoneNum']),
                      ],
                    )
                  ],
                )
              ],
            ),
          ),
        ],
      ),
      ),
            Container(
              height: 80.h,
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                      height: 35.h ,
                      margin: EdgeInsets.only(left: 30.w,right: 30.w),
                     
                      decoration: BoxDecoration(
                          color:MyColors.themeColor,
                          borderRadius: BorderRadius.all(Radius.circular(30))),
                      width: double.infinity,
                      child: TextButton(
                        child: Text("提交",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                        onPressed: (){
                          if(bankNum==""||bankName==""){
                            BrnToast.show("请添加银行卡信息", context,);
                          }else if(smsCode==""){
                            BrnToast.show("请输入验证码", context,);
                          }else{
                            ApiManager.postData(
                              context,
                              'api/pay/pay/shipper/bankcard/add',
                              {
                                "realName": userMap['realName'],
                                "idCard": userMap['idNum'],
                                "bankCard": bankNum,
                                "bankName": bankName,
                                "type": type,
                                "requestNo":validCodeReqNo,
                                "validCode":smsCode,
                              },
                                  (responseData) {
                                setState(() {
                                  BrnToast.show("添加成功", context,);
                                  Navigator.pop(context,"success");
                                });
                              },
                            );
                          }

                        },
                      )
                  ),
                ],
              ),
            ),
      ],
      ),

    );
  }
}
